<template>
  <div class="visitor-form">
    <van-nav-bar
      left-text="返回"
      @click-left="$router.back()"
      fixed
      title="发起申请"
      class="applyTitle"
    />
    <van-form @submit="submitForm">
      <!-- <form @submit.prevent="submitForm"> -->
      <van-cell-group>
        <van-field
          class="formItem"
          v-model="registrationNumber"
          label="登记编号"
          readonly
        ></van-field>
        <van-field
          v-model="visitorName"
          label="来访姓名"
          required
          placeholder="请输入来访姓名"
        ></van-field>
        <van-field
          v-model="idCardNumber"
          label="身份证号"
          placeholder="请输入身份证号"
          :rules="[
            { required: false, message: '请填写身份证号' },
            { validator: validateIdCardNumber, message: '身份证号格式不正确' },
          ]"
        ></van-field>
        <van-field
          v-model="contactPhone"
          label="联系手机"
          placeholder="请输入联系手机"
        ></van-field>
        <!-- <van-field
          v-model="visitTime"
          label="来访时间"
          readonly
          @click="showVisitTimePicker = true"
        ></van-field> -->
        <van-field
          readonly
          clickable
          :value="visitTime"
          label="来访时间"
          placeholder="点击选择来访时间"
          @click="showVisitTimePicker = true"
          required
          :rules="[{ required: false, message: '请填写来访时间' }]"
        />
        <!-- <van-field
          v-model="leaveTime"
          label="离开时间"
          readonly
          @click="showLeaveTimePicker = true"
        ></van-field> -->
        <van-field
          readonly
          clickable
          :value="leaveTime"
          label="离开时间"
          placeholder="点击选择离开时间"
          @click="showLeaveTimePicker = true"
          required
          :rules="[{ required: false, message: '请填写离开时间' }]"
        />
        <van-field
          v-if="type === 'car'"
          v-model="licensePlate"
          label="车牌号码"
          placeholder="请输入车牌号码"
        ></van-field>
        <van-field
          v-model="reason"
          label="来访事由"
          placeholder="请输入来访事由"
        ></van-field>
        <van-field
          v-model="inviterName"
          label="邀请人姓名"
          placeholder="请输入邀请人姓名"
        ></van-field>
        <van-field
          v-model="inviterPhone"
          label="邀请人手机号"
          placeholder="请输入邀请人手机号码"
        ></van-field>
        <van-field
          v-model="applicationTime"
          label="申请时间"
          readonly
        ></van-field>
      </van-cell-group>
      <van-cell class="switch-label" center title="是否通知该联系人">
        <template #right-icon>
          <van-switch v-model="isSend" size="24px" />
        </template>
      </van-cell>
      <van-button class="submitBtn" type="primary" native-type="submit"
        >提交</van-button
      >
      <van-button class="backBtn" type="danger" @click="returnBack"
        >返回</van-button
      >
      <!-- </form> -->
    </van-form>

    <van-popup v-model="showVisitTimePicker" position="bottom">
      <van-datetime-picker
        type="datetime"
        title="请选择来访时间"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="visitTimeConfirm"
      />
    </van-popup>
    <van-popup v-model="showLeaveTimePicker" position="bottom">
      <van-datetime-picker
        type="datetime"
        title="请选择离开时间"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="leaveTimeConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
/* eslint-disable */
import { DatetimePicker, Field, CellGroup, Popup, Toast } from "vant";
import { formatDate, getLocal } from "@/utils";
import { car_page, fangkexinxi_page, fangkexinxi_add, send_email } from "@/api";

export default {
  name: "apply-page",
  components: {
    [DatetimePicker.name]: DatetimePicker,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Popup.name]: Popup,
  },
  data() {
    return {
      registrationNumber: "",
      visitorName: "",
      idCardNumber: "",
      contactPhone: "",
      visitTime: "",
      leaveTime: "",
      licensePlate: "",
      reason: "",
      inviterName: "",
      inviterPhone: "",
      applicationTime: "",
      showVisitTimePicker: false,
      showLeaveTimePicker: false,
      minDate: new Date(),
      maxDate: new Date(2025, 10, 1),
      email: "",
      type: "",
      visitorData: {},
      isSend: false,
    };
  },
  methods: {
    async submitForm() {
      console.log("是否通知", this.isSend);
      if (!this.visitTime) {
        return Toast.fail("请填写来访时间!");
      }
      if (!this.leaveTime) {
        return Toast.fail("请填写离开时间!");
      }
      const payload = {
        dengjibianhao: this.registrationNumber,
        laifangxingming: this.visitorName,
        shenfenzheng: this.idCardNumber,
        lianxishouji: this.contactPhone,
        laifangshijian: this.visitTime,
        likaishijian: this.leaveTime,
        chepaihaoma: this.licensePlate,
        laifangshiyou: this.reason,
        xingming: this.inviterName,
        shoujihaoma: this.inviterPhone,
        shenqingshijian: this.applicationTime,
      };
      console.log("payload", payload);
      const res = await fangkexinxi_add(payload);
      if (res.code == 0) {
        if (this.isSend && this.email) {
          await send_email({
            to: this.email,
            subject: "港城大学访客预约平台 - 新邀请访客通知",
            content: `您有一名新的邀请访客 （${this.visitorData.name}）， 访客id为 ${this.visitorData.id} ，请注意查收  -- 来自港城大学访客预约平台（http://localhost:8081/）`,
          });
        }
        Toast.success("申请成功，请等待审批");
        this.$router.push("record");
      }
    },
    validateIdCardNumber(value) {
      if (value) return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
    },
    visitTimeConfirm(value) {
      this.visitTime = formatDate(value);
      this.showVisitTimePicker = false;
    },
    leaveTimeConfirm(value) {
      this.leaveTime = formatDate(value);
      this.showLeaveTimePicker = false;
    },
    generateRegistrationNumber() {
      const timestamp = Date.now();
      this.registrationNumber = timestamp.toString();
    },
    generateApplicationTime() {
      const now = new Date();
      this.applicationTime = formatDate(now);
    },
    returnBack(e) {
      e.preventDefault();
      this.$router.back();
    },
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }
      return val;
    },
    getDetail() {
      const visitorData = getLocal("visitorData");
      this.visitorData = visitorData;
      this.visitorName = visitorData.name;
      this.contactPhone = visitorData.phoneNum;
    },
    async carPage() {
      const res = await car_page({ visitorId: this.visitorData.id });
      if (res.code == 0 && res.data.list.length > 0) {
        this.licensePlate = res.data.list[0].num;
      }
    },
    async fangkexinxiPage() {
      const res = await fangkexinxi_page();
    },
    initData() {
      this.registrationNumber = "";
      this.visitorName = "";
      this.idCardNumber = "";
      this.contactPhone = "";
      this.visitTime = "";
      this.leaveTime = "";
      this.licensePlate = "";
      this.reason = "";
      this.inviterName = "";
      this.inviterPhone = "";
      this.applicationTime = "";
      this.showVisitTimePicker = false;
      this.showLeaveTimePicker = false;
      this.minDate = new Date();
      this.maxDate = new Date(2025, 10, 1);
      this.email = "";
      this.type = "";
      this.visitorData = {};
      this.isSend = false;
    },
  },
  created() {
    this.getDetail();
    this.generateRegistrationNumber();
    this.generateApplicationTime();
    this.carPage();

    if (this.$route.query.type) {
      this.type = this.$route.query.type;
    } else {
      this.type = "";
    }
    this.email = this.$route.query.email;
    this.inviterName = this.$route.query.inviterName;
    this.inviterPhone = this.$route.query.inviterPhone;
  },
  watch: {
    $route(to, from) {
      if (to.path === "/apply-detail") {
        this.initData();
        this.getDetail();
        this.generateRegistrationNumber();
        this.generateApplicationTime();
        this.carPage();
        if (to.query.type) {
          this.type = to.query.type;
        } else {
          this.type = "";
        }
        this.email = to.query.email;
        this.inviterName = to.query.inviterName;
        this.inviterPhone = to.query.inviterPhone;
      }
    },
    
  },
};
</script>

<style scoped>
.visitor-form {
  background-color: #f5f5f5;
  /* padding: 0 10px; */
  height: 100vh;
  margin-top: 40px;
  padding: 20px;
  .formItem {
    /* border: 3px solid red; */
    border-radius: 5px;
  }
}
.submitBtn {
  margin-left: 29vw;
  margin-top: 1vh;
  /* display: flex;
  justify-content: center; */
}

.backBtn {
  margin-left: 2vw;
}
</style>
